package NWish
{
	import NWish.Interface.IApp;
	
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	import org.aswing.*;

	public class UndoManager
	{
		private var _app:IApp;
		
		private var _undo:JMenuItem;
		private var _redo:JMenuItem;
		
		private var _doList:Array = [];
		private var _currDoIndex = -1;
		
		public function UndoManager(app)
		{
			//
			_app = app;
			
			
			//
			var menuBar:MenuBar = _app.getPlugin('MenuBar') as MenuBar;
			
			_undo = menuBar.editMenu.addMenuItem("Undo");
			_undo.setAccelerator(new KeySequence(KeyStroke.VK_CONTROL, KeyStroke.VK_Z));
			_undo.addActionListener(actionUndo);
			_undo.setEnabled(false);
			
			_redo = menuBar.editMenu.addMenuItem("Redo")
			_redo.setAccelerator(new KeySequence(KeyStroke.VK_CONTROL, KeyStroke.VK_Y));
			_redo.addActionListener(actionRedo);
			_redo.setEnabled(false);
			
			menuBar.editMenu.append(new JSeparator(JSeparator.HORIZONTAL));
			
			//
			_app.KBEventDispatcher.addEventListener(KeyboardEvent.KEY_UP, 		onKeyUp);
			
			//
			_app.NWEventDispatcher.addEventListener(NWEvent.CLEAR_SCENE,			onClearScene);
		}
		
		public function init()
		{
			
		}
		
		//
		private function onKeyUp(e:KeyboardEvent)
		{
			if(e.ctrlKey == false || e.shiftKey)
				return;
			
			if(e.keyCode == Keyboard.Z)
			{
				actionUndo(null);
			}
			else if(e.keyCode == Keyboard.Y)
			{
				actionRedo(null);
			}
		}
		
		//
		private function actionUndo(e)
		{
			if(_currDoIndex > -1)
			{
				_doList[_currDoIndex].undo();
				--_currDoIndex;
			
				_redo.setEnabled(true);
				if(_currDoIndex == -1)
					_undo.setEnabled(false)
			}
		}
		
		private function actionRedo(e)
		{
			if((_doList.length - 1) > _currDoIndex)
			{
				++_currDoIndex;
				_doList[_currDoIndex].redo();
				
				_undo.setEnabled(true);
				if((_doList.length - 1) == _currDoIndex)
					_redo.setEnabled(false)
			}
		}
		
		public function addDo(d)
		{
			if((_doList.length - 1) > _currDoIndex)
				_doList = _doList.slice(0,_currDoIndex + 1);

			_doList.push(d);
			++_currDoIndex;
			_undo.setEnabled(true);
			_redo.setEnabled(false);
		}

		public function clear()
		{
			_doList = [];
			_currDoIndex = -1;
			_undo.setEnabled(false);
			_redo.setEnabled(false);
		}
		
		private function onClearScene(e)
		{
			clear();
		}
	}
}